using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Media;

namespace VisualTail
{
    /// <summary>
    /// Tail.
    /// </summary>
    public partial class Tail : Form {

        delegate void SetTextCallback(string text);

        delegate void ProcessLoadFileCallback();

        /// <summary>
        /// Fuente de datos.
        /// </summary>
        public DSWorkflow ds = null;

        /// <summary>
        /// Constructor.
        /// </summary>
        public Tail() {
            InitializeComponent();          
        }

        /// <summary>
        /// Establece la fuente de datos.
        /// </summary>
        /// <param name="_ds"></param>
        public void SetDSWorkflow(DSWorkflow _ds) {
            this.ds = _ds;
        }

        private void SetText(string text) {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (tbViewFile.InvokeRequired) {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            } else {
                Application.DoEvents();
                this.tbViewFile.Text = text;
                checkBoxSonido_CheckedChanged(null, null);
                Application.DoEvents();
                checkBoxFuentes_CheckedChanged(null, null);
            }
        }

        void sp_LoadCompleted(object sender, AsyncCompletedEventArgs e) {
            SoundPlayer sp = (SoundPlayer)sender;
            sp.Play();
        }


        private void ProcessLoadFile() {

            if (lbFicheros.InvokeRequired) {
                ProcessLoadFileCallback d = new ProcessLoadFileCallback(ProcessLoadFile);
                Application.DoEvents();
                this.Invoke(d, null);
            } else {
                try{
                    //this.Cursor = Cursors.WaitCursor;
                    long filePos = 0;
                    long sizeRecover = 0;

                    Application.DoEvents();
                    this.Focus();
                    SetText("");
                    System.IO.FileInfo fich = (System.IO.FileInfo)lbFicheros.SelectedItem;

                    FileStream fs = new FileStream(fich.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    System.IO.StreamReader sr = new System.IO.StreamReader(fs, Encoding.Default);
                    sr.BaseStream.Seek(filePos, System.IO.SeekOrigin.Begin);
                    filePos = sr.BaseStream.Length;
                    sizeRecover = (long)(-1 * (numericUpDownKB.Value * 1024));
                    if ((filePos * - 1) > sizeRecover) {
                        sizeRecover = filePos * -1;
                    }
                    sr.BaseStream.Seek(sizeRecover, System.IO.SeekOrigin.End);
                    SetText(sr.ReadToEnd());
                    sr.Close();
                    tabPage1.Text = fich.Name;
                    this.ds.DTPalabras.ficheroColumn.DefaultValue = fich.Name;
                    this.Text = "Tail " + fich.Name;

                    Application.DoEvents();
                    checkBoxSonido_CheckedChanged(null, null);
                    Application.DoEvents();
                    checkBoxFuentes_CheckedChanged(null, null);
                }catch (System.Exception ex){
                    notifyIcon1.ShowBalloonTip(8, "Visual Tail", ex.Message, ToolTipIcon.Warning);
                    //MessageBox.Show(ex.Message);
                }finally {
                    //this.Cursor = Cursors.Default;
                }
                
            }
        
        }

        private void cargarFicheros() {
            this.folderBrowserDialog1.SelectedPath = tbPath.Text;
            if (DialogResult.OK == this.folderBrowserDialog1.ShowDialog()){
                tbPath.Text = this.folderBrowserDialog1.SelectedPath;
                //string []ficheros = System.IO.Directory.GetFiles(tbPath.Text);
                //lbFicheros.Items.AddRange(ficheros);

                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(tbPath.Text);
                lbFicheros.Items.Clear();
                lbFicheros.Items.AddRange(dir.GetFiles());
            };
        }

        private void btnPath_Click(object sender, EventArgs e) {
            cargarFicheros();
        }

        private void btnCargarFicheros_Click(object sender, EventArgs e){
            lbFicheros.Items.Clear();
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(tbPath.Text);
            try {
                lbFicheros.Items.AddRange(dir.GetFiles());
            } catch (Exception dnfe) {
                MessageBox.Show(dnfe.Message, "Visual Tail");
            }
        }

        private void btnFavoritos_Click(object sender, EventArgs e)
        {
            Directorios frm = new Directorios();
            frm.SetDSWorkflow(this.ds);
            frm.ShowDialog(this);
            //MessageBox.Show(frm.valorSeleccionado);
            tbPath.Text = frm.valorSeleccionado;
            btnCargarFicheros_Click(null, null);
        }

        private void Tail_Load(object sender, EventArgs e) {
            this.dTPalabrasBindingSource.DataSource = this.ds;
            this.dTRecursoBindingSource.DataSource = this.ds;
            this.dgPalabras.DataSource = this.ds.DTPalabras;
            this.dgPalabras.Refresh();
        }


        private void btnFuente_Click(object sender, EventArgs e)
        {
            fontDialog1.ShowDialog(this);
            checkBoxFuentes_CheckedChanged(null, null);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            colorDialogTexto.ShowDialog(this);
            btnColorTexto.ForeColor = colorDialogTexto.Color;
            checkBoxFuentes_CheckedChanged(null, null);
        }

        private void btnColorFondo_Click(object sender, EventArgs e)
        {
            colorDialogFondo.ShowDialog(this);
            btnColorFondo.BackColor = colorDialogFondo.Color;
            checkBoxFuentes_CheckedChanged(null, null);
        }

        private void checkBoxFuentes_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxFuentes.Checked) {
                
                //foreach (DSWorkflow.DTPalabrasRow palabra in this.ds.DTPalabras.Rows)
                System.IO.FileInfo fich = (System.IO.FileInfo)lbFicheros.SelectedItem;
                if (fich == null)
                {
                    return;
                }
                foreach (DSWorkflow.DTPalabrasRow palabra in this.ds.DTPalabras.Select("fichero is null or fichero='' or fichero='" + fich.Name + "'"))
                {
                    tbViewFile.SelectionStart = 0;
                    tbViewFile.SelectionLength = 0;

                    String word = palabra.idPalabra;
                    int pos = -1;
                    while ((pos = tbViewFile.Find(word, ++pos, RichTextBoxFinds.WholeWord)) != -1)
                    {
                        tbViewFile.SelectionStart = pos;
                        tbViewFile.SelectionLength = word.Length;
                        tbViewFile.SelectionFont = fontDialog1.Font;
                        tbViewFile.SelectionColor = colorDialogTexto.Color;
                        tbViewFile.SelectionBackColor = colorDialogFondo.Color;
                        Application.DoEvents();
                    }
                }
            }
        }

        private void checkBoxSonido_CheckedChanged(object sender, EventArgs e) {
            if (checkBoxSonido.Checked) {
                string texto = this.tbViewFile.Text.ToLower();
                System.IO.FileInfo fich = (System.IO.FileInfo)lbFicheros.SelectedItem;
                if (fich == null) {
                    return;
                }
                foreach (DSWorkflow.DTPalabrasRow palabra in this.ds.DTPalabras.Select("fichero is null or fichero='' or fichero='" + fich.Name + "'")) {
                    if (texto.IndexOf(palabra.idPalabra.ToLower()) > -1) {
                        try {
                            SoundPlayer sp = new SoundPlayer();
                            sp.LoadCompleted += new AsyncCompletedEventHandler(sp_LoadCompleted);
                            sp.SoundLocation = this.ds.DTRecurso.FindByidRecurso(cbSonido.Text).fichero_fisico;
                            sp.Load();
                        } catch (Exception ex) {
                            MessageBox.Show(ex.Message, "Visual Tail");
                        }
                    }
                    Application.DoEvents();

                }

            }//if (checkBoxSonido.Checked)
        }

        private void RestoreMe()
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Maximized;
            this.BringToFront();
            this.Focus();
        }

        /// <summary>
        /// Oculta cuando se minimiza.
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m){
            base.WndProc(ref m);
            if (((int)m.WParam & 0xFFF0) == 0xF020)
            {
                //MINIMIZANDO
                this.Visible = false;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            RestoreMe();
        }

        private void numericUpDownKB_ValueChanged(object sender, EventArgs e)
        {
            ProcessLoadFile();
        }

        private void lbFicheros_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


    }
}